<template>
  <div class="agent-model-provider-manager">
    <div class="action-bar">
      <div class="search-wrapper">
        <div class="search-input">
          <i class="search-icon el-icon-search"></i>
          <input 
            type="text" 
            v-model="keyword" 
            placeholder="搜索模型提供商名称或描述" 
            @keyup.enter="handleSearch"
          />
          <button class="search-btn" @click="handleSearch">搜索</button>
        </div>
      </div>
      
      <div class="action-buttons">
        <button class="btn-secondary" @click="handleRefreshDefault">
          <i class="btn-icon el-icon-refresh"></i>
          <span>刷新默认</span>
        </button>
        <button class="btn-primary" @click="handleCreateProvider">
          <i class="btn-icon el-icon-plus"></i>
          <span>创建模型提供商</span>
        </button>
      </div>
    </div>
    
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="providerList"
        style="width: 100%"
        :header-cell-style="{
          background: '#fafbfc',
          color: '#374151',
          fontWeight: '600',
          fontSize: '14px',
          padding: '16px 12px',
          borderBottom: '1px solid #e5e7eb'
        }"
        :row-style="{ height: '60px' }"
        :cell-style="{ padding: '12px' }"
      >
        <el-table-column prop="name" label="提供商名称" width="200">
          <template #default="{ row }">
            <div class="provider-info">
              <div class="provider-logo">
                <img v-if="row.logo" :src="row.logo" :alt="row.name" class="logo-img" />
                <i v-else class="el-icon-cpu logo-icon default-icon"></i>
              </div>
              <div class="provider-details">
                <el-tooltip 
                  v-if="row.aiModel" 
                  :content="`支持的AI模型: ${row.aiModel}`" 
                  placement="top"
                  effect="dark"
                >
                  <span class="provider-name-text">{{ row.name }}</span>
                </el-tooltip>
                <span v-else class="provider-name-text">{{ row.name }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" min-width="200">
          <template #default="{ row }">
            <div class="provider-describe" :title="row.description">{{ row.description }}</div>
          </template>
        </el-table-column>
        
        <el-table-column prop="baseUrl" label="API地址" width="180">
          <template #default="{ row }">
            <div class="api-url" :title="row.baseUrl">{{ row.baseUrl }}</div>
          </template>
        </el-table-column>
        
        <el-table-column prop="rateLimit" label="速率限制" width="100" align="center">
          <template #default="{ row }">
            <span class="rate-limit">{{ row.rateLimit }}/min</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="costPerToken" label="成本" width="100" align="center">
          <template #default="{ row }">
            <span class="cost-info">${{ row.costPerToken }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="priority" label="优先级" width="80" align="center">
          <template #default="{ row }">
            <span class="priority-badge" :class="getPriorityClass(row.priority)">{{ row.priority }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="isDefault" label="默认" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.isDefault" type="success" size="small">默认</el-tag>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch 
              v-model="row.status" 
              :active-value="1" 
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            <div class="time-info">
              <div class="time-text">{{ formatDate(row.createdAt) }}</div>
            </div>
          </template>
        </el-table-column>
        

        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="table-actions">
              <el-tooltip content="设为默认" placement="top">
                <button 
                  class="action-btn default-btn" 
                  @click="handleSetDefault(row)"
                  :disabled="row.isDefault"
                >
                  <i class="el-icon-star-on"></i>
                  <span class="btn-text">默认</span>
                </button>
              </el-tooltip>
              
              <el-tooltip content="编辑" placement="top">
                <button class="action-btn edit-btn" @click="handleEdit(row)">
                  <i class="el-icon-edit"></i>
                  <span class="btn-text">编辑</span>
                </button>
              </el-tooltip>
              
              <el-tooltip content="删除" placement="top">
                <button class="action-btn delete-btn" @click="handleDelete(row)">
                  <i class="el-icon-delete"></i>
                  <span class="btn-text">删除</span>
                </button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑模型提供商' : '创建模型提供商'"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="provider-dialog"
    >
      <div class="dialog-header">
        <h3 class="header-title">
          <i class="el-icon-cpu header-icon"></i>
          {{ isEdit ? '编辑模型提供商' : '创建模型提供商' }}
        </h3>
        <p class="header-subtitle">{{ isEdit ? '修改模型提供商配置信息' : '配置新的AI模型提供商' }}</p>
      </div>
      
      <div class="dialog-content">
        <!-- 表单错误提示 -->
        <div v-if="formErrors.length > 0" class="form-errors">
          <i class="error-icon el-icon-warning"></i>
          <div class="error-list">
            <p v-for="(error, index) in formErrors" :key="index" class="error-item">{{ error }}</p>
          </div>
        </div>

        <el-form 
          ref="formRef"
          :model="providerForm" 
          :rules="formRules"
          label-width="120px"
          class="provider-form"
          label-position="top"
        >
          <div class="form-row">
            <el-form-item label="提供商名称" prop="name" class="form-item">
              <el-input 
                v-model="providerForm.name" 
                placeholder="请输入提供商名称"
                prefix-icon="el-icon-cpu"
                size="large"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="API地址" prop="baseUrl" class="form-item">
              <el-input 
                v-model="providerForm.baseUrl" 
                placeholder="请输入API地址"
                prefix-icon="el-icon-link"
                size="large"
                @input="handleApiConfigChange"
              />
            </el-form-item>
            
            <el-form-item label="API版本" prop="apiVersion" class="form-item">
              <el-input 
                v-model="providerForm.apiVersion" 
                placeholder="请输入API版本"
                prefix-icon="el-icon-document"
                size="large"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="Logo地址" prop="logo" class="form-item full-width">
              <el-input 
                v-model="providerForm.logo" 
                placeholder="请输入Logo图片地址"
                prefix-icon="el-icon-picture"
                size="large"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="认证Token" prop="authToken" class="form-item">
              <el-input 
                v-model="providerForm.authToken" 
                type="password"
                placeholder="请输入API认证Token"
                prefix-icon="el-icon-key"
                size="large"
                show-password
                @blur="handleApiConfigChange"
              />
            </el-form-item>
            
            <el-form-item label="是否需要授权" prop="role" class="form-item">
              <el-select v-model="providerForm.role" placeholder="请选择是否需要授权" class="full-width" size="large">
                <el-option :value="1" label="是" />
                <el-option :value="0" label="否" />
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="速率限制" prop="rateLimit" class="form-item">
              <el-input-number 
                v-model="providerForm.rateLimit" 
                :min="1"
                :max="10000"
                placeholder="每分钟请求次数"
                size="large"
                class="full-width"
              />
            </el-form-item>
            
            <el-form-item label="每Token成本" prop="costPerToken" class="form-item">
              <el-input-number 
                v-model="providerForm.costPerToken" 
                :min="0"
                :precision="6"
                :step="0.000001"
                placeholder="美元"
                size="large"
                class="full-width"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="最大Token数" prop="maxTokens" class="form-item">
              <el-input-number 
                v-model="providerForm.maxTokens" 
                :min="1"
                :max="1000000"
                placeholder="最大Token数量"
                size="large"
                class="full-width"
              />
            </el-form-item>
            
            <el-form-item label="超时时间(秒)" prop="timeout" class="form-item">
              <el-input-number 
                v-model="providerForm.timeout" 
                :min="1"
                :max="300"
                placeholder="请求超时时间"
                size="large"
                class="full-width"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="AI模型" prop="aiModel" class="full-width">
              <!-- 第一行：AI模型选择器 -->
              <div class="model-selector-row">
                <el-select
                  v-model="selectedModels"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  placeholder="选择AI模型"
                  :remote-method="filterModels"
                  :loading="modelsLoading"
                  size="large"
                  class="model-select"
                  @change="handleModelChange"
                >
                  <template #empty>
                    <div class="empty-models">
                      <div v-if="modelsLoading" class="loading-state">
                        <i class="el-icon-loading"></i>
                        <p>加载模型中...</p>
                      </div>
                      <div v-else class="no-models">
                        <i class="el-icon-search"></i>
                        <p>未找到匹配的模型</p>
                      </div>
                    </div>
                  </template>
                  
                  <el-option
                    v-for="model in filteredModels"
                    :key="model"
                    :label="model"
                    :value="model"
                  >
                    <div class="model-option">
                      <span class="model-name">{{ model }}</span>
                      <span v-if="selectedModels.includes(model)" class="model-selected"> ✔</span>
                    </div>
                  </el-option>
                </el-select>
                
                <el-button 
                  v-if="canLoadModels" 
                  type="primary" 
                  size="large" 
                  :loading="modelsLoading"
                  @click="loadModelList"
                  class="refresh-models-btn"
                >
                  {{ modelsLoading ? '加载中...' : '刷新模型' }}
                </el-button>
              </div>
              
              <!-- 第二行：手动输入模型 -->
              <div class="manual-input-row">
                <el-input
                  v-model="manualModelInput"
                  placeholder="手动输入模型名称（如：gpt-4、claude-3-sonnet等）"
                  size="large"
                  class="manual-model-input"
                  @keyup.enter="addManualModel"
                >
                  <template #prepend>
                    <span>手动输入模型</span>
                  </template>
                </el-input>
                <el-button 
                  type="primary" 
                  size="large"
                  @click="addManualModel"
                  :disabled="!manualModelInput.trim()"
                  class="add-model-btn"
                >
                  添加
                </el-button>
              </div>
              
              <!-- 第三行：已选择的模型 -->
              <div class="selected-models-row">
                <div class="selected-models-container">
                  <span class="models-label">已选择的模型 ({{ selectedModels.length }})：</span>
                  <div class="model-tags-area">
                    <template v-if="selectedModels.length > 0">
                      <el-tag 
                        v-for="model in selectedModels" 
                        :key="model" 
                        type="success" 
                        size="default"
                        closable
                        @close="removeModel(model)"
                        class="model-tag"
                      >
                        {{ model }}
                      </el-tag>
                    </template>
                    <template v-else>
                      <span class="empty-hint">暂未选择任何模型</span>
                    </template>
                  </div>
                </div>
              </div>
              
              <!-- 帮助提示 -->
              <div class="model-help-text">
                <i class="el-icon-info"></i>
                <span>支持从API获取模型列表或手动输入模型名称，选中的模型将用逗号拼接传给后端</span>
              </div>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="温度参数" prop="temperature" class="form-item">
              <el-input-number 
                v-model="providerForm.temperature" 
                :min="0"
                :max="2"
                :precision="2"
                :step="0.1"
                placeholder="0.0-2.0"
                size="large"
                class="full-width"
              />
            </el-form-item>
            
            <el-form-item label="优先级" prop="priority" class="form-item">
              <el-input-number 
                v-model="providerForm.priority" 
                :min="1"
                :max="100"
                placeholder="数值越小优先级越高"
                size="large"
                class="full-width"
              />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="状态" prop="status" class="form-item">
              <el-select v-model="providerForm.status" placeholder="请选择状态" class="full-width" size="large">
                <el-option :value="1" label="启用" />
                <el-option :value="0" label="禁用" />
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="描述" prop="description" class="form-item full-width">
              <el-input 
                v-model="providerForm.description" 
                type="textarea"
                :rows="4"
                placeholder="请输入提供商描述信息"
                resize="both"
                size="large"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" @click="handleDialogClose">取消</el-button>
          <el-button type="primary" size="large" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '保存' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  getAgentModelProviderList,
  createAgentModelProvider,
  updateAgentModelProvider,
  deleteAgentModelProvider,
  setDefaultAgentModelProvider,
  getDefaultAgentModelProvider,
  getModelList,
  type AgentModelProviderInfo,
  type AgentModelProviderPageRequest,
  type AgentModelProviderCreateDTO,
  type AgentModelProviderUpdateDTO,
} from '../api/agentModelProvider'

// 响应式数据
const loading = ref(false)
const providerList = ref<AgentModelProviderInfo[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const keyword = ref('')

// 新增：模型相关数据
const availableModels = ref<string[]>([])
const selectedModels = ref<string[]>([])
const modelsLoading = ref(false)
const modelSearchText = ref('') // 新增：模型搜索文本
const manualModelInput = ref('') // 新增：手动输入模型名称

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const editId = ref<number | null>(null)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const formErrors = ref<string[]>([])

// 表单数据
const providerForm = reactive<AgentModelProviderCreateDTO>({
  name: '',
  baseUrl: '',
  authToken: '',
  apiVersion: '',
  rateLimit: 60,
  costPerToken: 0.000001,
  maxTokens: 4096,
  timeout: 30,
  temperature: 0.7,
  priority: 10,
  role: 0,
  aiModel: '',
  logo: '',
  description: '',
  status: 1
})



// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入提供商名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  baseUrl: [
    { required: true, message: '请输入API地址', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
  ],
  authToken: [
    { required: true, message: '请输入认证Token', trigger: 'blur' }
  ],
  aiModel: [
    { required: true, message: '请输入AI模型名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { min: 5, max: 500, message: '描述长度在 5 到 500 个字符', trigger: 'blur' }
  ],
  rateLimit: [
    { required: true, message: '请设置速率限制', trigger: 'change' }
  ],
  costPerToken: [
    { required: true, message: '请设置Token成本', trigger: 'change' }
  ],
  maxTokens: [
    { required: true, message: '请设置最大Token数', trigger: 'change' }
  ],
  timeout: [
    { required: true, message: '请设置超时时间', trigger: 'change' }
  ],
  temperature: [
    { required: true, message: '请设置温度参数', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请设置优先级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 获取提供商列表
const fetchProviderList = async () => {
  loading.value = true
  try {
    const params: AgentModelProviderPageRequest = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: keyword.value
    }
    const res = await getAgentModelProviderList(params)
    providerList.value = res.data.items
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取提供商列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchProviderList()
}

// 分页变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchProviderList()
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchProviderList()
}

// 计算属性：是否可以加载模型（API地址和Token都已填写）
const canLoadModels = computed(() => {
  return providerForm.baseUrl && providerForm.authToken
})

// 计算属性：过滤后的模型列表（支持前缀匹配）
const filteredModels = computed(() => {
  if (!modelSearchText.value) {
    return availableModels.value
  }
  const searchLower = modelSearchText.value.toLowerCase()
  return availableModels.value.filter(model => 
    model.toLowerCase().startsWith(searchLower)
  )
})

// 保留API配置变化的处理函数，只在baseUrl或authToken变化时清空模型
const handleApiConfigChange = () => {
  // 清空已选择的模型和可用模型列表
  selectedModels.value = []
  availableModels.value = []
  providerForm.aiModel = ''
  modelSearchText.value = ''
}



// 优化：加载模型列表（添加缓存和错误处理）
const loadModelList = async () => {
  if (!canLoadModels.value) {
    ElMessage.warning('请先填写API地址和认证Token')
    return
  }
  
  // 如果已经有模型列表，不重复加载
  if (availableModels.value.length > 0) {
    return
  }
  
  try {
    modelsLoading.value = true
    const response = await getModelList(providerForm.baseUrl, providerForm.authToken)
    if (response.data && Array.isArray(response.data)) {
      // 直接使用字符串数组
      availableModels.value = response.data
      ElMessage.success(`成功获取到 ${response.data.length} 个模型`)
    } else {
      availableModels.value = []
      ElMessage.warning('未获取到模型列表')
    }
  } catch (error) {
    console.error('获取模型列表失败:', error)
    ElMessage.error('获取模型列表失败，请检查API地址和认证Token是否正确')
    availableModels.value = []
  } finally {
    modelsLoading.value = false
  }
}

// 处理模型选择变化
const handleModelChange = (models?: string[]) => {
  if (models) {
    selectedModels.value = models
  }
  // 将选中的模型用逗号拼接给 aiModel 字段
  providerForm.aiModel = selectedModels.value.join(',')
}

// 移除单个模型
const removeModel = (modelName: string) => {
  const index = selectedModels.value.indexOf(modelName)
  if (index > -1) {
    selectedModels.value.splice(index, 1)
    // Call the unified function to update aiModel
    handleModelChange()
  }
}

// 新增：添加手动输入的模型
const addManualModel = () => {
  const modelName = manualModelInput.value.trim()
  if (!modelName) {
    ElMessage.warning('请输入模型名称')
    return
  }
  
  // 检查是否已存在
  if (selectedModels.value.includes(modelName)) {
    ElMessage.warning('该模型已存在')
    return
  }
  
  // 添加到选中列表
  selectedModels.value.push(modelName)
  handleModelChange(selectedModels.value)
  
  // 清空输入框
  manualModelInput.value = ''
  
  ElMessage.success(`已添加模型: ${modelName}`)
}

// 处理模型搜索输入
const filterModels = (query: string) => {
  modelSearchText.value = query
}

// 创建提供商
const handleCreateProvider = () => {
  isEdit.value = false
  editId.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑提供商
const handleEdit = async (row: AgentModelProviderInfo) => {
  isEdit.value = true
  editId.value = row.id
  
  // 填充表单数据
  Object.assign(providerForm, row)
  
  // 解析已选择的模型
  if (row.aiModel) {
    selectedModels.value = row.aiModel.split(',')
  } else {
    selectedModels.value = []
  }
  
  // 重置搜索
  modelSearchText.value = ''
  
  dialogVisible.value = true
}

// 删除提供商
const handleDelete = (row: AgentModelProviderInfo) => {
  ElMessageBox.confirm(
    `确定要删除提供商 "${row.name}" 吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteAgentModelProvider(row.id)
      ElMessage.success('删除成功')
      fetchProviderList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 设置默认提供商
const handleSetDefault = async (row: AgentModelProviderInfo) => {
  try {
    await setDefaultAgentModelProvider(row.id)
    ElMessage.success('设置默认成功')
    fetchProviderList()
  } catch (error) {
    ElMessage.error('设置默认失败')
  }
}

// 状态变化
const handleStatusChange = async (row: AgentModelProviderInfo) => {
  try {
    const updateData: AgentModelProviderUpdateDTO = {
      id: row.id,
      name: row.name,
      baseUrl: row.baseUrl,
      authToken: row.authToken,
      apiVersion: row.apiVersion,
      rateLimit: row.rateLimit,
      costPerToken: row.costPerToken,
      maxTokens: row.maxTokens,
      timeout: row.timeout,
      temperature: row.temperature,
      priority: row.priority,
      role: row.role,
      aiModel: row.aiModel,
      logo: row.logo,
      description: row.description,
      status: row.status
    }
    await updateAgentModelProvider(updateData)
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 刷新默认提供商
const handleRefreshDefault = async () => {
  try {
    await getDefaultAgentModelProvider()
    ElMessage.success('刷新成功')
    fetchProviderList()
  } catch (error) {
    ElMessage.error('刷新失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    formErrors.value = []
    submitting.value = true
    
    if (isEdit.value && editId.value) {
      const updateData: AgentModelProviderUpdateDTO = {
        id: editId.value,
        ...providerForm
      }
      await updateAgentModelProvider(updateData)
      ElMessage.success('更新成功')
    } else {
      await createAgentModelProvider(providerForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchProviderList()
  } catch (error: any) {
    if (error.fields) {
      // 表单验证错误
      formErrors.value = Object.values(error.fields).flat().map((item: any) => item.message)
    } else {
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(providerForm, {
    id: undefined, // 确保清除 id 字段
    name: '',
    baseUrl: '',
    authToken: '',
    apiVersion: '',
    rateLimit: 60,
    costPerToken: 0.000001,
    maxTokens: 4096,
    timeout: 30,
    temperature: 0.7,
    priority: 1,
    role: '',
    aiModel: '',
    logo: '',
    description: '',
    status: 1
  })
  
  // 重置模型选择
  selectedModels.value = []
  availableModels.value = []
  modelSearchText.value = ''
  manualModelInput.value = '' // 新增：清空手动输入
  providerForm.aiModel = ''
  
  formErrors.value = []
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 工具函数
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getPriorityClass = (priority: number) => {
  if (priority <= 3) return 'priority-high'
  if (priority <= 7) return 'priority-medium'
  return 'priority-low'
}

// 生命周期
onMounted(() => {
  fetchProviderList()
})
</script>

<style scoped lang="scss">
.agent-model-provider-manager {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;
}

/* 操作栏样式 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 20px;
  
  .search-wrapper {
    flex: 1;
    max-width: 500px;
  }
  
  .search-input {
    position: relative;
    display: flex;
    align-items: center;
    
    .search-icon {
      position: absolute;
      left: 16px;
      color: #9ca3af;
      font-size: 16px;
      z-index: 1;
    }
    
    input {
      flex: 1;
      height: 48px;
      padding: 0 16px 0 44px;
      border: 2px solid #e5e7eb;
      border-radius: 12px 0 0 12px;
      font-size: 14px;
      outline: none;
      transition: all 0.3s ease;
      background: white;
      
      &:focus {
        border-color: #6366f1;
        box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
      }
      
      &::placeholder {
        color: #9ca3af;
      }
    }
    
    .search-btn {
      height: 48px;
      padding: 0 24px;
      background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
      color: white;
      border: none;
      border-radius: 0 12px 12px 0;
      cursor: pointer;
      font-weight: 500;
      transition: all 0.3s ease;
      
      &:hover {
        background: linear-gradient(135deg, #5856eb 0%, #7c3aed 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
      }
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 12px;
    
    .btn-primary, .btn-secondary {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px 20px;
      border: none;
      border-radius: 12px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s ease;
      font-size: 14px;
      
      .btn-icon {
        font-size: 16px;
      }
    }
    
    .btn-primary {
      background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
      color: white;
      box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
      
      &:hover {
        background: linear-gradient(135deg, #5856eb 0%, #7c3aed 100%);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
      }
    }
    
    .btn-secondary {
      background: white;
      color: #6b7280;
      border: 2px solid #e5e7eb;
      
      &:hover {
        background: #f9fafb;
        border-color: #d1d5db;
        color: #374151;
      }
    }
  }
}

/* 表格样式 */
.table-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  border: 1px solid #f1f5f9;
  
  :deep(.el-table) {
    border-radius: 16px;
    
    .el-table__header {
      th {
        background: #fafbfc !important;
        border-bottom: 1px solid #e5e7eb;
      }
    }
    
    .el-table__row {
      transition: all 0.3s ease;
      
      &:hover {
        background: #f8fafc;
      }
    }
  }
  
  .pagination-wrapper {
    padding: 20px;
    display: flex;
    justify-content: center;
    border-top: 1px solid #f1f5f9;
  }
}

/* 提供商信息样式 */
.provider-info {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .provider-logo {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
    
    .logo-img {
      width: 32px;
      height: 32px;
      border-radius: 6px;
      object-fit: cover;
    }
    
    .logo-icon {
      font-size: 20px;
      color: white;
      
      &.default-icon {
        opacity: 0.8;
      }
    }
  }
  
  .provider-details {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      
      .provider-name-text {
        font-weight: 500;
        color: #303133;
        font-size: 14px;
        display: block;
        margin-bottom: 2px;
        cursor: help;
      }
    }
}

.provider-describe {
  color: #6b7280;
  line-height: 1.5;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.api-url {
  color: #6366f1;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.rate-limit, .cost-info {
  font-weight: 500;
  color: #374151;
}

.priority-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 24px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  
  &.priority-high {
    background: #fee2e2;
    color: #dc2626;
  }
  
  &.priority-medium {
    background: #fef3c7;
    color: #d97706;
  }
  
  &.priority-low {
    background: #dcfce7;
    color: #16a34a;
  }
}

.text-muted {
  color: #9ca3af;
}

.time-info {
  .time-text {
    color: #6b7280;
    font-size: 13px;
  }
}

/* 操作按钮样式 */
.table-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
  padding-left: 8px;
  
  .action-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 8px 12px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 12px;
    font-weight: 500;
    min-width: 55px;
    justify-content: center;
    white-space: nowrap;
    
    .btn-text {
      font-size: 11px;
    }
    
    &.default-btn {
      background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
      color: #d97706;
      border: 1px solid #fbbf24;
      
      &:hover:not(:disabled) {
        background: linear-gradient(135deg, #fde68a 0%, #fcd34d 100%);
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(217, 119, 6, 0.3);
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
    
    &.edit-btn {
      background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
      color: #1d4ed8;
      border: 1px solid #93c5fd;
      
      &:hover {
        background: linear-gradient(135deg, #bfdbfe 0%, #93c5fd 100%);
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(29, 78, 216, 0.3);
      }
    }
    
    &.delete-btn {
      background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
      color: #dc2626;
      border: 1px solid #f87171;
      
      &:hover {
        background: linear-gradient(135deg, #fecaca 0%, #f87171 100%);
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(220, 38, 38, 0.3);
      }
    }
  }
}

/* 对话框样式 */
:deep(.provider-dialog) {
  .el-dialog {
    border-radius: 16px;
    overflow: hidden;
  }
  
  .el-dialog__header {
    padding: 0;
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 0;
  }
}

.dialog-header {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  padding: 24px;
  position: relative;
  
  .header-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 20px;
    font-weight: 600;
    margin: 0 0 8px 0;
    
    .header-icon {
      font-size: 24px;
    }
  }
  
  .header-subtitle {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
  }
}

.dialog-content {
  padding: 32px;
  max-height: 70vh;
  overflow-y: auto;
  
  .form-errors {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 16px;
    background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
    border: 1px solid #fecaca;
    border-radius: 12px;
    margin-bottom: 24px;
    
    .error-icon {
      color: #ef4444;
      font-size: 18px;
      margin-top: 2px;
    }
    
    .error-list {
      flex: 1;
      
      .error-item {
        margin: 0;
        color: #dc2626;
        font-size: 14px;
        line-height: 1.5;
        
        &:not(:last-child) {
          margin-bottom: 4px;
        }
      }
    }
  }
  
  .provider-form {
    :deep(.el-form-item) {
      margin-bottom: 24px;
      
      .el-form-item__label {
        font-weight: 500;
        color: #374151;
        margin-bottom: 8px;
      }
      
      .el-input, .el-select, .el-input-number {
        width: 100%;
        
        .el-input__inner, .el-select__wrapper {
          border-radius: 8px;
          border: 2px solid #e5e7eb;
          transition: all 0.3s ease;
          
          &:hover {
            border-color: #d1d5db;
          }
          
          &:focus, &.is-focus {
            border-color: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
          }
        }
        
        &.is-error {
          .el-input__inner, .el-select__wrapper {
            border-color: #ef4444;
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.1);
          }
        }
        
        &:focus {
          box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }
      }
    }
    
    .form-row {
      display: flex;
      gap: 20px;
      
      .form-item {
        flex: 1;
        
        &.full-width {
          flex: 1 1 100%;
        }
      }
    }
  }
}

.dialog-footer {
  padding: 24px 32px;
  background: #f9fafb;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.full-width {
  width: 100%;
}

/* 固定三行布局样式 */
.model-selector-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  align-items: center;
  min-height: 40px;
  
  .model-select {
    flex: 1;
    min-width: 0;
  }
  
  .refresh-models-btn {
    flex-shrink: 0;
    min-width: 100px;
  }
}

.manual-input-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  align-items: center;
  min-height: 40px;
  
  .manual-model-input {
    flex: 1;
    min-width: 0;
    
    :deep(.el-input-group__prepend) {
      background: #f8fafc;
      border-color: #e5e7eb;
      color: #374151;
      font-weight: 500;
      min-width: 120px;
      padding: 0 15px;
    }
  }
  
  .add-model-btn {
    flex-shrink: 0;
    min-width: 80px;
    background: #3b82f6;
    border-color: #3b82f6;
    
    &:disabled {
      background: #9ca3af;
      border-color: #9ca3af;
      color: #f3f4f6;
      cursor: not-allowed;
    }
    
    &:not(:disabled):hover {
      background: #2563eb;
      border-color: #2563eb;
    }
    
    &:not(:disabled):active {
      background: #1d4ed8;
      border-color: #1d4ed8;
    }
  }
}

.selected-models-row {
  margin-bottom: 12px;
  min-height: 40px;
  
  .selected-models-container {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    
    .models-label {
      font-size: 14px;
      color: #606266;
      font-weight: 500;
      white-space: nowrap;
      margin-top: 6px;
      min-width: 140px;
    }
    
    .model-tags-area {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      min-height: 32px;
      align-items: flex-start;
      
      .empty-hint {
        color: #909399;
        font-size: 14px;
        font-style: italic;
        margin-top: 6px;
      }
    }
  }
}

.model-tag {
  margin: 0;
  font-weight: 500;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
}

.model-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.model-name {
  font-weight: 500;
  color: #303133;
}

.model-desc {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.model-selected {
  color: #67c23a;
  font-weight: bold;
  margin-left: 8px;
}

.empty-models {
  padding: 20px;
  text-align: center;
}

.loading-state, .no-models {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #909399;
}

.loading-state i, .no-models i {
  font-size: 24px;
}

.model-help-text {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #6b7280;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 4px;
  
  i {
    color: #3b82f6;
    flex-shrink: 0;
  }
}

.full-width {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .agent-model-provider-manager {
    padding: 16px;
  }
  
  .action-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
    
    .search-wrapper {
      max-width: none;
    }
    
    .action-buttons {
      justify-content: center;
    }
  }
  
  .dialog-content {
    padding: 20px;
    
    .provider-form {
      .form-row {
        flex-direction: column;
        gap: 0;
      }
    }
  }
  
  .table-actions {
    flex-direction: column;
    gap: 4px;
    
    .action-btn {
      min-width: 50px;
      padding: 6px 8px;
      
      .btn-text {
        display: none;
      }
    }
  }
  
  .model-selector-row {
    flex-direction: column;
    gap: 8px;
    
    .refresh-models-btn {
      width: 100%;
    }
  }
  
  .manual-input-row {
    flex-direction: column;
    gap: 8px;
    
    .add-model-btn {
      width: 100%;
    }
  }
  
  .selected-models-row {
    .selected-models-container {
      flex-direction: column;
      gap: 8px;
      
      .models-label {
        min-width: auto;
      }
    }
  }
}


</style>